﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Red.Controls.Diagrams.ViewModels;
using Red.Controls.ViewModels;

namespace Red.Controls.Diagrams.Actions.InteropActions
{
    class AddConnectedNodeAction : InteropActionBase
    {
        #region Data

        readonly ActionConnectionData _connectionData;

        #endregion Data

        #region C-tor

        public AddConnectedNodeAction( DataItem parentObject, string className, Point position, DiagramViewModel viewModel, ConnectionViewModel connection, Func<string, Task> nodeCreator )
        {
            var connector = connection.SourceConnector;

            _nodeData = new ActionNodeData
            {
                ClassName = className,
                Position = position,
                NodeID = string.Empty,
            };

            _connectionData = new ActionConnectionData
            {
                Connection = connection,
                OutputID = connector.ID,
                OutputOwnerID = connector.ParentNode.ID,
                ValueID = Red.GameData.Raw.Utils.FormatGuid( Guid.NewGuid() )
            };

            _parentObject = parentObject;
            _viewModel = viewModel;
            _nodeCreator = nodeCreator;
        }

        #endregion C-tor

        #region Public methods

        public async Task ExecuteAsync()
        {
            var operationID = Guid.NewGuid().ToString();
            var nodeID = await CreateNodeAsync( _nodeData, _parentObject, operationID );
            var node = _viewModel.FindNode( nodeID );

            var inputConnector = node.InputConnectors.FirstOrDefault();
            _connectionData.InputID = inputConnector.ID;
            _connectionData.InputOwnerID = node.ID;
            CreateConnection( _connectionData, operationID );
        }

        #endregion Public methods
    }
}
